<template>
  <div
    class="copyright1"
    style="
      display: flex;
      margin-bottom: 20px;
      height: 60px;
      width: 100vw;
      justify-content: space-between;
    "
  >
    <div class="left" style="margin-left: 10px; display: flex; width: 80%">
      <span style="font-size: 50px; color: black; font-weight: bold">
        VICHI.
      </span>
      <ul
        class="nav-list"
        style="display: flex; list-style: none; margin: 15px; padding: 0"
      >
        <li class="nav-item" :class="{ active: $route.path === '/' }">
          <router-link to="/" style="font-weight: bold">首页</router-link>
        </li>
        <li
          class="nav-item"
          :class="{ active: $route.path === '/companionship' }"
        >
          <router-link to="/companionship" style="font-weight: bold"
            >智伴优学</router-link
          >
        </li>
        <li class="nav-item" :class="{ active: $route.path === '/ask' }">
          <router-link to="/ask" style="font-weight: bold"
            >睿记精解</router-link
          >
        </li>
        <li class="nav-item" :class="{ active: $route.path === '/ask' }">
          <router-link to="/ask" style="font-weight: bold"
            >心聆秘语</router-link
          >
        </li>
      </ul>
    </div>
    <div class="right" style="display: flex; width: 20%">
      <div style="padding: 10px; margin-left: 60px">
        <el-avatar
          shape="square"
          size="default"
          src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
          style="border: 2px solid black; margin-top: 10px"
        />
      </div>
      <div style="margin-left: 10px; margin-top: 30px">
        <span style="font-weight: bold; font-size: 20px">Zoe</span>
      </div>
    </div>
  </div>

  <div
    style="
      display: flex;
      height: 110vh;
      width: 100vw;
      position: relative;
      overflow-x: hidden;
      background-image: url(/src/assets/背景.png);
      background-size: cover;
      background-repeat: no-repeat;
      filter: blur(0);
    "
  >
    <div class="left" style="width: calc(100% - 30%)">
      <!-- 动态计算宽度 -->
      <div
        class="camera"
        style="
          background-color: white;
          border-radius: 20px;
          height: 350px;
          width: 500px;
          margin-top: 100px;
          margin-left: 200px;
          display: flex; /* 启用 Flex 布局 */
          justify-content: center; /* 水平居中 */
          /* align-items: center; 垂直居中 */
        "
      >
        <div>
          <div
            class="stu"
            style="
              background-color: antiquewhite;
              border-radius: 20px;
              height: 280px;
              width: 450px;
              margin-top: 20px;
              overflow: hidden;
              position: relative;
            "
          >
            <!-- 添加video元素用于显示摄像头画面 -->
            <video
              ref="videoElement"
              autoplay
              style="
                width: 100%;
                height: 100%;
                object-fit: cover;
                display: none;
              "
            ></video>
          </div>
          <div style="display: flex; justify-content: center; margin-top: 10px">
            <span style="font-size: 15px; font-weight: bold">状态:</span>
            <span
              style="font-size: 15px; font-weight: bold; margin-left: 10px"
              :style="{ color: cstatus === '开启' ? 'green' : 'inherit' }"
              >{{ cstatus }}</span
            >
          </div>
        </div>
      </div>
      <div
        class="button-box"
        style="
          display: flex;
          margin-left: 250px;
          width: 400px;
          height: 50px;
          margin-top: 20px;
        "
      >
        <div
          class="button-1"
          style="
            height: 50px;
            width: 120px;
            background-color: black;
            border-radius: 20px;
            margin-left: 20px;
            text-align: center; /* 水平居中 */
          "
        >
          <h2
            style="color: white; line-height: 50px; margin: 0"
            @click="startCamera"
          >
            开启
          </h2>
        </div>
        <div
          class="button-2"
          style="
            height: 50px;
            width: 120px;
            background-color: black;
            border-radius: 20px;
            margin-left: 120px;
            text-align: center; /* 水平居中 */
          "
        >
          <h2
            style="color: white; line-height: 50px; margin: 0"
            @click="stopCamera"
          >
            关闭
          </h2>
        </div>
      </div>
      <div style="margin-top: 130px; width: 90%">
        <div style="display: flex">
          <el-col :span="8" style="display: flex; margin-left: 50px">
            <el-countdown
              v-if="isTaskRunning || isTaskTimeout"
              title="任务倒计时"
              :value="value"
            />
            <div v-else-if="isTaskPaused" class="paused-countdown">
              <h2 style="color: white">
                已暂停:{{ formatTime(pausedRemainingTime) }}
              </h2>
            </div>
          </el-col>
          <el-button
            size="large"
            round
            style="display: flex; margin-left: 250px; font-weight: bold"
            @click="startTask"
            :disabled="isTaskRunning"
            >{{ isTaskRunning ? "任务进行中" : "开始任务" }}</el-button
          >
          <el-button
            size="large"
            round
            style="
              display: flex;
              font-weight: bold;
              margin-left: 50px;
              background-color: black;
            "
            @click="pauseTask"
            :disabled="!isTaskRunning"
            ><h3 style="color: white">暂停任务</h3></el-button
          >
        </div>

        <div
          class="time-box"
          style="
            height: 30px;
            background-color: white;
            margin-top: 20px;
            margin-left: 50px;
            border-radius: 15px;
            overflow: hidden;
          "
        >
          <div
            class="progress-bar"
            :style="{
              width: progress + '%',
              height: '100%',
              backgroundColor: progressColor,
              transition: 'width 1s linear',
            }"
          ></div>
        </div>
      </div>
    </div>
    <div
      class="right"
      :style="{
        width: isExpanded ? '30%' : '0',
        backgroundColor: 'rgba(245, 249, 255, 0.5)',
        overflow: 'hidden',
        transition: 'width 0.3s ease',
        position: 'fixed',
        right: 0,
        height: '100%',
        top: 0,
        bottom: 0,
      }"
    >
      <div
        v-if="isExpanded"
        style="
          height: 300px;
          max-width: 100px;
          margin-top: 50px;
          margin-left: 50px;
        "
      >
        <div style="width: 300px">
          <h2>今日任务:</h2>
        </div>
        <div>
          <el-steps
            direction="vertical"
            :active="getCurrentPageActiveStep"
            finish-status="success"
            :space="80"
          >
            <!-- 分页显示步骤，每页3个 -->
            <el-step
              v-for="(step, index) in paginatedSteps"
              :key="index + (currentPage - 1) * 3"
              :title="`任务 ${(currentPage - 1) * 3 + index + 1}`"
              :class="{
                'completed-step': step.status === '1',
                'timeout-step': step.status === '2',
                'unstarted-step': step.status === '0',
              }"
            >
              <template #description>
                <div
                  class="step-description"
                  style="
                    background-color: white;
                    width: 300px;
                    border-radius: 10px;
                  "
                >
                  <div style="padding: 5px; padding-left: 15px">
                    <h2 style="">{{ step.description }}</h2>
                    <div class="expected-time">
                      <i class="el-icon-time"></i>
                      <h3>
                        计划完成耗时：{{ step.hour }}小时{{ step.min }}分钟
                      </h3>
                    </div>
                    <div>
                      <h3>
                        完成情况：
                        <span v-if="step.status === 0">{{
                          isTaskRunning &&
                          currentStep === (currentPage - 1) * 3 + index
                            ? "进行中"
                            : "当前未执行"
                        }}</span>
                        <span
                          v-else-if="step.status === 1"
                          style="color: #67c23a"
                          >已完成</span
                        >
                        <span
                          v-else-if="step.status === 2"
                          style="color: #f56c6c"
                          >超时完成</span
                        >
                      </h3>
                    </div>
                  </div>
                  <div style="display: flex; margin-left: 100px">
                    <el-button
                      round
                      @click="openEditForm(step, index + (currentPage - 1) * 3)"
                      style="
                        display: flex;
                        background-color: white;
                        width: 70px;
                        text-align: center;
                        border: 2px solid black;
                        margin-left: 20px;
                      "
                    >
                      <span
                        style="color: black; font-size: 15px; font-weight: bold"
                        >修改</span
                      >
                    </el-button>
                    <el-button
                      round
                      @click="deleteTask(index + (currentPage - 1) * 3)"
                      style="
                        display: flex;
                        background-color: black;
                        width: 70px;
                        text-align: center;
                        margin-left: 20px;
                      "
                    >
                      <span
                        style="color: white; font-size: 15px; font-weight: bold"
                        >删除</span
                      >
                    </el-button>
                  </div>
                </div>
              </template>
            </el-step>
          </el-steps>
        </div>

        <!-- 分页控件 - 左侧 -->

        <el-pagination
          v-if="steps.length != 0"
          layout="prev, pager, next"
          :total="steps.length"
          :page-size="3"
          @current-change="handlePageChange"
          :current-page="currentPage"
          style="margin-left: 120px; margin-top: 20px"
        />

        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 300px;
            height: 100px;
            position: relative;
            padding: 0 20px;
          "
        >
          <el-button
            round
            size="large"
            @click="completeStep"
            :disabled="currentStep >= steps.length"
            style="
              display: flex;
              background-color: black;
              width: 150px;
              text-align: center;
              border: none;
            "
          >
            <span style="color: white; font-size: 15px; font-weight: bold"
              >当前任务已完成</span
            >
          </el-button>

          <el-button
            round
            size="large"
            @click="showAddForm = true"
            style="
              display: flex;
              background-color: white;
              width: 170px;
              text-align: center;
              border: none;
              margin-left: 20px;
            "
          >
            <span style="color: black; font-size: 15px; font-weight: bold"
              >添加新任务</span
            >
          </el-button>
        </div>
      </div>
    </div>

    <div
      style="
        position: absolute;
        bottom: 30px;
        left: 85%;
        transform: translateX(-50%);
        width: 100%;
        text-align: center;
      "
    >
      <el-button
        size="large"
        round
        style="background-color: white"
        @click="togglePanel"
      >
        <h2 style="color: black">
          {{ isExpanded ? "关闭" : "查看任务详情" }}
        </h2>
      </el-button>
    </div>
  </div>
  <div
    class="footer"
    style="width: 100%; height: 40px; background-color: white"
  >
    <div class="copyright">
      <span style="margin-top: 10px">Copyright © 2025 薇启Vichi 版权所有</span>
    </div>
  </div>

  <el-dialog title="提示" v-model="showCompletionDialog" width="30%">
    <span>恭喜你完成今日任务</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="showCompletionDialog = false"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>

  <!-- 在模板底部添加对话框 -->
  <el-dialog
    title="新增任务"
    v-model="showAddForm"
    style="width: 500px; border-radius: 15px; border: 2px solid black"
    :close-on-click-modal="false"
  >
    <el-form :model="sizeForm" label-width="100px" style="padding: 20px">
      <el-form-item label="任务描述">
        <el-input
          v-model="sizeForm.description"
          type="textarea"
          placeholder="请输入任务描述"
          style="width: 320px"
        />
      </el-form-item>
      <el-form-item label="计划时间">
        <div style="display: flex">
          <el-input v-model="sizeForm.hour" style="width: 50px"></el-input>小时
          <el-input v-model="sizeForm.min" style="width: 50px"></el-input>分钟
          <el-button
            round
            style="
              background-color: black;
              width: 130px;
              text-align: center;
              border: none;
              margin-left: 30px;
            "
            @click="getAITime"
          >
            <h4 style="color: white">AI推荐任务时间</h4>
          </el-button>
        </div>
      </el-form-item>

      <div style="margin-left: 80px; margin-top: 30px">
        <el-button
          round
          @click="showAddForm = false"
          style="
            background-color: white;
            width: 80px;
            text-align: center;
            border-color: black;
            margin-left: 30px;
          "
          ><h4 style="color: black">取消</h4></el-button
        >
        <el-button
          round
          @click="addTask()"
          style="
            background-color: white;
            width: 80px;
            text-align: center;
            border-color: black;
            margin-left: 30px;
          "
          ><h4 style="color: black">确定</h4></el-button
        >
      </div>
    </el-form>
  </el-dialog>

  <el-dialog
    title="修改任务"
    v-model="showEditForm"
    style="width: 500px; border-radius: 15px; border: 2px solid black"
    :close-on-click-modal="false"
  >
    <el-form :model="sizeForm" label-width="100px" style="padding: 20px">
      <el-form-item label="任务描述">
        <el-input
          v-model="sizeForm.description"
          type="textarea"
          placeholder="请输入任务描述"
          style="width: 320px"
        />
      </el-form-item>
      <el-form-item label="计划时间">
        <div style="display: flex">
          <el-input v-model="sizeForm.hour" style="width: 50px"></el-input>小时
          <el-input v-model="sizeForm.min" style="width: 50px"></el-input>分钟
          <el-button
            round
            style="
              background-color: black;
              width: 130px;
              text-align: center;
              border: none;
              margin-left: 30px;
            "
            @click="getAITime"
          >
            <h4 style="color: white">AI推荐任务时间</h4>
          </el-button>
        </div>
      </el-form-item>

      <div style="margin-left: 80px; margin-top: 30px">
        <el-button
          round
          @click="showEditForm = false"
          style="
            background-color: white;
            width: 80px;
            text-align: center;
            border-color: black;
            margin-left: 30px;
          "
          ><h4 style="color: black">取消</h4></el-button
        >
        <el-button
          round
          @click="editTask"
          style="
            background-color: white;
            width: 80px;
            text-align: center;
            border-color: black;
            margin-left: 30px;
          "
          ><h4 style="color: black">确定</h4></el-button
        >
      </div>
    </el-form>
  </el-dialog>
</template>

<script>
import { onUnmounted } from "vue";
import { getCurrentInstance } from "vue";

export default {
  data() {
    return {
      showEditForm: false,
      cstatus: "关闭",
      videoStream: null, // 用于存储摄像头流
      value: 0,
      isExpanded: false,
      currentPage: 1,
      timeout: false,
      showCompletionDialog: false,
      showAddForm: false,
      sizeForm: {
        // 表单数据模型
        description: "",
        hour: 0,
        min: 0,
        status: 0,
      },
      labelPosition: "right", // 表单标签位置（可选）
      size: "medium", // 表单控件尺寸（可选）
      currentStep: 0, // 当前激活的步骤（从 0 开始）
      isTaskRunning: false, // 任务是否正在进行
      taskDuration: 0, // 任务总时长(毫秒)
      startTime: 0, // 任务开始时间
      progress: 0, // 进度百分比
      progressInterval: null, // 进度条定时器
      progressColor: "#67C23A", // 进度条颜色
      isTaskTimeout: false, // 任务是否超时（倒计时结束且未及时确认）
      timeoutDeadline: null, // 超时判定截止时间（倒计时结束时间+5分钟）
      duration: 0,
      steps: [
        // {
        //   description: "task1eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
        //   hour: 1,
        //   min: 20,
        //   status: 2, //0：未完成，1：已完成，2：超时完成
        // },
        // {
        //   description: "task2",
        //   hour: 1,
        //   min: 20,
        //   status: 2, //0：未完成，1：已完成，2：超时完成
        // },
        // {
        //   description: "task3",
        //   hour: 1,
        //   min: 20,
        //   status: 2, //0：未完成，1：已完成，2：超时完成
        // },
      ], // 初始化为空数组
      currentTaskId: 0,
      isTaskPaused: false,
      savedCountdownValue: 0,
      isEditTime: false,
      id: 0,
      // 新增：记录当前页的第一个任务索引
      currentPageFirstIndex: 0,
    };
  },
  computed: {
    // 新增：计算当前页的活动步骤
    getCurrentPageActiveStep() {
      const start = (this.currentPage - 1) * 3;
      const currentPageSteps = this.steps.slice(start, start + 3);
      const activeIndex = currentPageSteps.findIndex(
        (step) => step.status === 0
      );
      return activeIndex === -1 ? currentPageSteps.length : activeIndex;
    },
    paginatedSteps() {
      const start = (this.currentPage - 1) * 3;
      const end = start + 3;
      return this.steps.slice(start, end);
    },
    // 新增：计算当前页中已完成的任务数量
    completedTasksInCurrentPage() {
      return this.paginatedSteps.filter(
        (step) => step.status === 1 || step.status === 2
      ).length;
    },
    isCurrentPageCompleted() {
      return this.paginatedSteps.every(
        (step) => step.status === 1 || step.status === 2
      );
    },
    isAllCompleted() {
      return this.steps.every((step) => step.status === 1 || step.status === 2);
    },
  },
  methods: {
    async deleteTask(taskId) {
      try {
        const response = await this.$apiAxios.delete(`/tasks/${taskId}`);
        if (response.data.code == 200) {
          this.$message.success("删除任务成功");
          // 判断当前执行任务是否被删除
          if (this.currentStep === taskId) {
            // 清除本地状态并重置
            localStorage.removeItem("vichi_task_state");
            this.isTaskRunning = false;
            this.isTaskPaused = false;
            this.progress = 0;
            this.value = 0;
            this.progressColor = "#67C23A";
          }
          await this.getTasks();
        } else {
          this.$message.error(response.data.msg || "删除任务失败");
        }
      } catch {
        this.$message.error("删除任务失败");
      }
    },
    openEditForm(step, taskId) {
      console.log("taskId", taskId);
      this.showEditForm = true;
      this.sizeForm.description = step.description;
      this.sizeForm.hour = step.hour;
      this.sizeForm.min = step.min;
      this.sizeForm.status = step.status;

      this.currentTaskId = taskId;
    },
    async editTask() {
      try {
        this.isEditTime = true;
        const taskData = {
          description: this.sizeForm.description,
          hour: parseInt(this.sizeForm.hour),
          min: parseInt(this.sizeForm.min),
          status: this.sizeForm.status,
        };
        const taskIndex = this.currentTaskId;
        const response = await this.$apiAxios.put(
          `/tasks/${taskIndex}`,
          taskData
        );
        console.log(response);
        if (response.data.code == 200) {
          this.$message.success("更新任务成功");
          // 清空表单
          this.sizeForm = {
            description: "",
            hour: "",
            min: "",
            status: 0,
          };
          // 关闭对话框
          this.showEditForm = false;
          // 重新获取任务列表
          await this.getTasks();
        } else {
          this.$message.error(response.data.msg || "更新任务失败");
        }
      } catch {
        console.error("更新任务失败:", error);
        this.$message.error("更新任务失败");
      }
    },
    async addTask() {
      try {
        // 构建任务数据
        const taskData = {
          description: this.sizeForm.description,
          hour: parseInt(this.sizeForm.hour) || 0,
          min: parseInt(this.sizeForm.min) || 0,
          status: 0,
        };

        // 发送 POST 请求
        const response = await this.$apiAxios.post("/tasks", taskData);

        if (response.data && response.data.code === 200) {
          this.$message.success("添加任务成功");
          // 清空表单
          this.sizeForm = {
            description: "",
            hour: "",
            min: "",
          };
          // 关闭对话框
          this.showAddForm = false;
          // 重新获取任务列表
          await this.getTasks();
        } else {
          this.$message.error(response.data.msg || "添加任务失败");
        }
      } catch (error) {
        console.error("添加任务失败:", error);
        this.$message.error("添加任务失败");
      }
    },
    // 获取任务列表
    // 获取任务列表
    async getTasks() {
      try {
        const response = await this.$apiAxios.get("/tasks");
        console.log(response.data);
        if (
          response.data &&
          response.data.code === 200 &&
          response.data.tasksList
        ) {
          this.steps = response.data.tasksList.map((taskStr) => {
            const task = JSON.parse(taskStr);
            return {
              description: task.description,
              hour: task.hour,
              min: task.min,
              status: task.status, // 新增：解析status字段
            };
          });
          // 新增：自动设置当前任务为第一个未完成的任务
          this.setCurrentStepByStatus();
        } else {
          this.steps = [];
          this.currentStep = 0;
        }
      } catch (error) {
        console.error("获取任务列表失败:", error);
        this.$message.error("获取任务列表失败");
        this.steps = [];
      }
    },
    // 新增方法：根据任务状态设置当前步骤
    setCurrentStepByStatus() {
      // 查找第一个status为0的任务索引
      const firstUncompletedIndex = this.steps.findIndex(
        (step) => step.status === 0
      );

      // 如果找到未完成任务，设置为当前步骤；否则设为-1（表示所有任务已完成）
      this.currentStep =
        firstUncompletedIndex === -1 ? -1 : firstUncompletedIndex;
    },
    async startCamera() {
      try {
        this.cstatus = "开启";
        // 显示video元素
        this.$refs.videoElement.style.display = "block";

        // 获取摄像头权限并开启
        this.videoStream = await navigator.mediaDevices.getUserMedia({
          video: true,
          audio: false,
        });

        // 将摄像头流赋给video元素
        this.$refs.videoElement.srcObject = this.videoStream;
      } catch (error) {
        console.error("访问摄像头出错:", error);
        this.cstatus = "错误";
        // 可以在这里添加用户提示
      }
    },
    stopCamera() {
      this.cstatus = "关闭";
      if (this.videoStream) {
        // 停止所有轨道并移除监听器
        this.videoStream.getTracks().forEach((track) => {
          track.stop(); // 停止轨道
          track.enabled = false; // 禁用轨道
        });
        // 清除视频源
        this.$refs.videoElement.srcObject = null;
        this.videoStream = null;

        // 强制释放video元素
        this.$refs.videoElement.pause();
        this.$refs.videoElement.removeAttribute("src");
        this.$refs.videoElement.load();

        // 隐藏video元素
        this.$refs.videoElement.style.display = "none";
      }
    },
    saveTaskState() {
      const today = new Date().toISOString().slice(0, 10); // 'YYYY-MM-DD'
      const state = {
        date: today,
        isTaskRunning: this.isTaskRunning,
        isTaskPaused: this.isTaskPaused,
        currentStep: this.currentStep,
        startTime: this.startTime,
        taskDuration: this.taskDuration,
        pausedElapsedTime: this.pausedElapsedTime || 0,
        remainingDuration: this.remainingDuration || 0,
        value: this.value,
        progress: this.progress,
        progressColor: this.progressColor,
        isTaskTimeout: this.isTaskTimeout,
        pausedRemainingTime: this.pausedRemainingTime || 0,
      };
      localStorage.setItem("vichi_task_state", JSON.stringify(state));
    },
    loadTaskState() {
      const stateStr = localStorage.getItem("vichi_task_state");
      if (!stateStr) return;
      try {
        const state = JSON.parse(stateStr);
        const today = new Date().toISOString().slice(0, 10);
        if (state.date !== today) {
          // 不是今天的，清理
          localStorage.removeItem("vichi_task_state");
          return;
        }
        this.isTaskRunning = state.isTaskRunning;
        this.isTaskPaused = state.isTaskPaused;
        this.currentStep = state.currentStep;
        this.startTime = state.startTime;
        this.taskDuration = state.taskDuration;
        this.pausedElapsedTime = state.pausedElapsedTime;
        this.remainingDuration = state.remainingDuration;
        this.value = state.value;
        this.progress = state.progress;
        this.progressColor = state.progressColor;
        this.isTaskTimeout = state.isTaskTimeout;
        this.pausedRemainingTime = state.pausedRemainingTime;
      } catch (e) {
        // ignore
      }
    },
    startTask() {
      if (this.currentStep >= this.steps.length) return;

      // 如果是从暂停状态恢复
      if (this.isEditTime) {
        // 从暂停时保存的时间点继续
        this.taskDuration =
          (this.steps[this.currentStep].hour * 3600 +
            this.steps[this.currentStep].min * 60) *
          1000;

        this.startTime = Date.now();
        this.value = Date.now() + this.taskDuration;
        this.isTaskPaused = false;
      } else if (this.isTaskPaused) {
        this.startTime = Date.now() - this.pausedElapsedTime;
        this.value = Date.now() + this.remainingDuration;
        this.isTaskPaused = false;
      } else {
        // 新任务开始
        this.taskDuration =
          (this.steps[this.currentStep].hour * 3600 +
            this.steps[this.currentStep].min * 60) *
          1000;

        this.startTime = Date.now();
        this.value = Date.now() + this.taskDuration;
      }

      this.isTaskRunning = true;
      this.progressColor = "#67C23A";
      this.updateProgress();
      this.progressInterval = setInterval(this.updateProgress, 1000);
      this.saveTaskState(); // 新增
    },
    // 更新进度条
    updateProgress() {
      const elapsed = Date.now() - this.startTime;
      this.progress = Math.min(100, (elapsed / this.taskDuration) * 100);

      // 倒计时结束时触发超时逻辑
      if (elapsed >= this.taskDuration) {
        this.stopTask();
        // 设置超时判定截止时间（当前时间+5分钟）
        console.log("超时了！！！");
        this.isTaskTimeout = true; // 先标记为超时，后续根据点击状态修正

        // 倒计时结束但未超时期间，进度条显示红色
        this.progressColor = "#F56C6C";
      } else if (this.taskDuration - elapsed < this.taskDuration * 0.1) {
        // 剩余时间不足10%时显示橙色
        this.progressColor = "#E6A23C";
      }
      this.saveTaskState(); // 新增
    },
    // 停止任务
    stopTask() {
      clearInterval(this.progressInterval);
      this.progressInterval = null;
      this.isTaskRunning = false;
      this.saveTaskState(); // 新增
    },
    // 暂停任务
    pauseTask() {
      if (!this.isTaskRunning) return;

      clearInterval(this.progressInterval);
      this.progressInterval = null;

      // 计算已用时间和剩余时间
      this.pausedElapsedTime = Date.now() - this.startTime;
      this.remainingDuration = this.taskDuration - this.pausedElapsedTime;

      // 保存当前倒计时值，但暂停时显示为null使倒计时组件暂停
      this.savedCountdownValue = this.value;
      this.value = null;

      // 计算暂停时剩余的时间（毫秒）
      this.pausedRemainingTime = this.remainingDuration;

      this.isTaskRunning = false;
      this.isTaskPaused = true; // 标记为暂停状态
      this.saveTaskState(); // 新增
    },
    // 格式化时间（毫秒 -> HH:MM:SS格式）
    formatTime(milliseconds) {
      const totalSeconds = Math.floor(milliseconds / 1000);
      const hours = Math.floor(totalSeconds / 3600);
      const minutes = Math.floor((totalSeconds % 3600) / 60);
      const seconds = totalSeconds % 60;

      return [
        hours.toString().padStart(2, "0"),
        minutes.toString().padStart(2, "0"),
        seconds.toString().padStart(2, "0"),
      ].join(":");
    },
    togglePanel() {
      this.isExpanded = !this.isExpanded;
    },
    // 完成步骤时检查是否在超时时间内
    async completeStep() {
      const currentTaskIndex = this.currentStep;
      if (currentTaskIndex < this.steps.length) {
        console.log("isTaskTimeout", this.isTaskTimeout);
        if (this.isTaskTimeout) {
          try {
            //超时：
            const response = await this.$apiAxios.put(
              `/tasks/${currentTaskIndex}/2`
            );
            console.log("超时完成更新成功", response);
            this.isTaskTimeout = false;
            await this.getTasks();
          } catch {
            console.error("更新完成状态失败:", error);
            this.$message.error("更新完成状态失败");
          }
        } else {
          //未超时：
          try {
            const response = await this.$apiAxios.put(
              `/tasks/${currentTaskIndex}/1`
            );
            console.log("未超时完成更新成功", response);
            await this.getTasks();
          } catch {
            console.error("更新完成状态失败:", error);
            this.$message.error("更新完成状态失败");
          }
        }

        this.value = 0; // 清空倒计时
        this.progress = 0; // 进度条归零
        this.progressColor = "#67C23A"; // 恢复绿色
        this.stopTask();
        localStorage.removeItem("vichi_task_state"); // 完成后清除

        // 更新当前步骤
        this.setCurrentStepByStatus();

        // 检查是否需要翻页
        if (this.isCurrentPageCompleted && !this.isAllCompleted) {
          this.currentPage++;
        }

        // 检查是否所有任务都已完成
        if (this.currentStep === -1) {
          this.showCompletionDialog = true;
        }
      }
    },
    handlePageChange(val) {
      this.currentPage = val;
    },
    async getAITime() {
      try {
        const response = await this.$agentAxios.post("/ai-time", {
          task: this.sizeForm.description || "默认任务",
        });
        if (response.data) {
          this.sizeForm.hour = response.data.hour;
          this.sizeForm.min = response.data.min;
          console.log(response.data);
        }
      } catch (error) {
        console.error("获取AI推荐时间失败:", error);
        this.$message.error("获取AI推荐时间失败");
      }
    },
  },
  mounted() {
    this.videoElement = this.$refs.videoElement;
    this.getTasks().then(() => {
      this.loadTaskState(); // 新增
      // 如果任务正在进行或暂停，恢复倒计时/进度条
      if (this.isTaskRunning) {
        // 重新计算剩余时间
        const elapsed = Date.now() - this.startTime;
        if (elapsed < this.taskDuration) {
          this.value = Date.now() + (this.taskDuration - elapsed);
          this.progressInterval = setInterval(this.updateProgress, 1000);
          this.updateProgress();
        } else {
          this.isTaskTimeout = true;
          this.progress = 100;
          this.progressColor = "#F56C6C";
        }
      } else if (this.isTaskPaused) {
        // 保持暂停状态
        // this.value = null; // 已在loadTaskState中恢复
      }
    });
  },
  beforeUnmount() {
    // 组件销毁前关闭摄像头
    this.stopCamera();
  },
  // 组件卸载时清除定时器
  onUnmounted() {
    if (this.progressInterval) {
      clearInterval(this.progressInterval);
    }
  },
  watch: {
    steps() {
      this.setCurrentStepByStatus();
    },
    currentPage() {
      this.setCurrentStepByStatus();
    },
    currentStep(newVal) {
      console.log(`Step changed to: ${newVal}`);
      if (newVal === -1) {
        // 修改判断条件
        console.log("All steps completed (from watcher)");
        this.showCompletionDialog = true;
      }
    },
  },
};
</script>

<style scoped>
/* 移除分页组件整体背景色 */
.el-pagination {
  background-color: transparent !important;
}

/* 移除分页按钮的背景色（hover/active 状态可选） */
.el-pagination .el-pager li,
.el-pagination .el-pager li:not(.disabled):hover,
.el-pagination .el-pager li.active {
  background-color: transparent !important;
  color: black;
}

/* 移除前后翻页按钮背景色 */
.el-pagination .btn-next,
.el-pagination .btn-prev {
  background-color: transparent !important;
  color: black;
}
.el-col {
  text-align: center;
}

.countdown-footer {
  margin-top: 8px;
}
.el-step__icon-inner {
  color: black;
}
.el-statistic__head {
  color: white;
  font-size: 20px;
  font-family: "Arial", sans-serif;
  font-weight: var(--el-statistic-title-font-weight);
  line-height: 20px;
  margin-bottom: 4px;
}
.el-statistic__number {
  font-weight: bold;
  font-size: 30px;
  color: white;
}

/* 如果需要自定义颜色，可以覆盖 Element UI 默认样式 */
.el-step__head.is-success {
  color: #000000; /* 深绿色 */
  border-color: #000000;
}
.progress-bar {
  transition: width 1s linear;
}
.custom-steps-container {
  padding: 20px;
  max-width: 400px; /* 控制宽度，防止过长 */
}
/* 已完成样式 */
.completed-step .el-step__head,
.completed-step .el-step__title {
  color: #67c23a !important;
  border-color: #67c23a !important;
}

/* 超时完成样式 */
.timeout-step .el-step__head,
.timeout-step .el-step__title {
  color: #f56c6c !important;
  border-color: #f56c6c !important;
}

/* 未开始样式 */
.unstarted-step .el-step__head,
.unstarted-step .el-step__title {
  color: #909399 !important;
  border-color: #dcdfe6 !important;
}

/* 进行中样式 */
.el-step__head.is-process {
  color: black !important;
  border-color: black !important;
}

.copyright {
  text-align: center;
  font-size: 12px;
  color: #888;
  margin-top: 10px;
}
.nav-list {
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0;
}

.nav-item {
  margin-left: 25px;
  font-size: 20px;
  font-weight: 500;
}

.nav-item a {
  color: #333;
  text-decoration: none; /* 去除下划线 */
  padding: 8px 12px;
  border-radius: 4px;
  transition: all 0.3s ease;
  display: block;
}

.nav-item a:hover {
  background-color: #defcf9;
}

.nav-item.active a {
  border: 2px solid black;
}

.el-form-item__label {
  align-items: flex-start;
  box-sizing: border-box;
  color: black;
  display: inline-flex;
  flex: 0 0 auto;
  font-size: var(--el-form-label-font-size);
  height: 32px;
  line-height: 32px;
  padding: 0 12px 0 0;
}

.el-step__icon.is-text {
  border: 2px solid;
  border-radius: 5px;
}
.el-step__head.is-process {
  color: #000000;
}
.step-description h2 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: bold;
  line-height: 1.5;
  max-width: 280px; /* 限制最大宽度 */
  white-space: normal; /* 允许文本换行 */
  word-break: break-word; /* 单词内换行 */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 最多显示2行 */
}
</style>
